import json
import os.path
import time

from flask import Blueprint, request, jsonify

api = Blueprint('api', __name__)


@api.route('/upload', methods=['POST', "GET"])
def upload():
    if request.method == 'GET':
        return 'Hello'
    # 创建文件夹
    current_directory = os.getcwd()
    folder_path = os.path.join(current_directory, 'upload')
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    file = request.files['file']
    name = time.strftime('%Y%m%d%H%M%S') + '-' + file.filename
    file.save(os.path.join(current_directory, 'upload', name))
    return jsonify({'pic':name})

@api.route('/submit',methods=['POST'])
def submit():
    name = time.strftime('%Y%m%d%H%M%S')
    data = request.json
    data['addTime'] = time.strftime('%Y-%m-%d %H:%M:%S')
    with open(f'./output/{name}-{data["pageIndex"]}.json', 'a',encoding='utf-8') as f:
        json.dump(data, f,ensure_ascii=False, indent=4)

    return jsonify({'success':True})

@api.route('/preview/<id_>',methods=['POST'])
def preview(id_):
    with open(f'./output/{id_}.json','r',encoding='utf-8') as f:
        file = json.load(f)
    return jsonify(file)

@api.route('/admin',methods=['GET'])
def admin():
    return jsonify(os.listdir('output'))